package com.github.gin.sns.util;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.SecureRandom;

public class HTTPSUtil {
	public static String doRequest(String url,String reqMethod,String params){
		String result = "";
		BufferedReader br = null;
		try{
			TrustManager[] tm  =  {new MyX509TrustManager()};
			SSLContext ssl = SSLContext.getInstance("SSL", "SunJSSE");
			ssl.init(null, tm, new SecureRandom());
			SSLSocketFactory factory = ssl.getSocketFactory();
			
			URL target = new URL(url);
			HttpsURLConnection https = (HttpsURLConnection) target.openConnection();
			https.setSSLSocketFactory(factory);
			
			https.setDoInput(true);
			https.setDoOutput(true);
			https.setRequestMethod(reqMethod);
			if("GET".equalsIgnoreCase(reqMethod))
				https.connect();
			
			if(params != null){
				OutputStream os = https.getOutputStream();
				os.write(params.getBytes("UTF-8"));
				os.close();
			}
			
			br = new BufferedReader(new InputStreamReader(https.getInputStream(),"UTF-8"));
			String line = "";
			while((line=br.readLine()) != null){
				result += line;
			}
			
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(br != null ){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	
	
	
}
